package com.ldzy.controller;

import com.alibaba.fastjson.JSONObject;
import com.ldzy.pojo.Record;
import com.ldzy.pojo.User;
import com.ldzy.service.IRecordService;
import com.ldzy.service.IUserService;
import com.ldzy.utilts.RespUtil;
import javafx.animation.KeyFrame;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
        @Resource
    IUserService iUserService;
        @Resource
    IRecordService iRecordService;
    @PostMapping("/login")
    public RespUtil login(@RequestBody User user, HttpServletRequest request) {
        System.out.println(user.toString());
        try {
            User user1 = iUserService.login(user);
            if (user1 != null) {
                request.getSession().setAttribute("USER_LOGIN", user1);
                System.out.println(user1.toString());

                return RespUtil.success("登陆成功", user1);
            }
            return RespUtil.error("登录失败,密码错误！");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return RespUtil.error("登录失败，系统错误");
        }
    }

    @PostMapping("/logout")
    public RespUtil logout(HttpServletRequest request) {
        System.out.println("退出登录");
        System.out.println(request.getRequestURI());
        try {
            HttpSession session = request.getSession();
            session.invalidate();
            System.out.println("注销成功");
            return RespUtil.success("注销成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RespUtil.error("注销失败，系统错误");
        }
    }
    @PutMapping("/updatePwd")
    public  RespUtil updatePwd(@RequestBody User user){
        if (user.getUserPassword().length()>=6){
            return  iUserService.updatePwd(user);
        }
        return  RespUtil.error("密码不足六位！！！");
    }
    @PostMapping("/add")
    public  RespUtil addUser(@RequestBody User user){
        System.out.println("adduser");
        System.out.println(user.toString());
        Calendar c=Calendar.getInstance();
        String time=new SimpleDateFormat("yyyy-MM-ddHHmmss").format(c.getTime()).toString();
        StringBuffer s=new StringBuffer(time.substring(14, 16));
        Long sys=System.currentTimeMillis();
        s.append(sys.toString().substring(11, 13));
        Double tm=Math.random()*10000+1;
        s.append(tm.toString().substring(tm.toString().length()-7, tm.toString().length()));
        System.out.println(s);
       int phone=user.getUserPhone().length();
       int password=user.getUserPassword().length();
        if (phone!=11||password<6){
            return  RespUtil.error("手机号与密码格式不正确！！");
        }
        if (user.getUserImage()!=null&&user.getUserBirth()!=null&&user.getUserSex()!=null
                &&user.getUserName()!=null){
            if(iUserService.isPhone(user)){
                return RespUtil.error("该手机已经注册过了！！！");

            }
            user.setUserAccount(s.toString());
            User user1 =new User();
            user1.setUserAccount(s.toString());
            if(iUserService.adduser(user))
            {
             return    RespUtil.success("注册成功！！！",s.toString());
            }

        }
        return  RespUtil.error("注册失败！！！");
    }
   @PutMapping("/updateUserMoney")
    public  RespUtil updateUserMoney(@RequestBody JSONObject map){
       Record record =new Record();
       User user =new User();
       Long id = map.getLong("userId");
       double money = map.getDouble("userMoney");
       String type = map .getString("type");
       record.setMoney(money);
       record.setTime(LocalDateTime.now());
       record.setUserId(id);
       record.setType(type);
       user.setUserId(id);
       user.setUserMoney(money);
        if (iUserService.updateUserMoney(user))
        {
            if(iRecordService.save(record)){
                return  RespUtil.success("充值成功！！",iUserService.getById(user.getUserId()));
            }
        }
        return  RespUtil.error("充值失败！！！");
   }
    @PutMapping("/updateInformation")
    public  RespUtil updateInformation(@RequestBody JSONObject map){
          int imageIndex=map.getInteger("imageIndex");
          User user =new User();
          Long id = map.getLong("userId");
          user.setUserId(id);
          String phone=map.getString("userPhone");
        System.out.println(phone);
        user.setUserPhone(phone);
        if (user.getUserPhone().length()!=11||user.getUserPhone()==null){
            return  RespUtil.error("手机号码格式不正确！！");
        }

          if(imageIndex==0){
                user= iUserService.getById(id);
                phone = user.getUserPhone();
          }
          else {
              user.setUserImage(map.getString("userImage"));
          }
          user.setUserName(map.getString("userName"));
          user.setUserBirth(map.getString("userBirth"));
        user.setUserPhone(phone);
          user.setUserIndividuation(map.getString("userIndividuation"));
          user.setUserAccount(map.getString("userAccount"));
          user.setUserSex(map.getString("userSex"));


        if (iUserService.updateInformation(user)){
            if(iUserService.isPhone(user)&&!user.getUserPhone().equals(phone)){
                return RespUtil.error("手机号码已经注册过了！！");
            }
            return  RespUtil.success(iUserService.getById(user.getUserId()));
        }
        return  RespUtil.error();
    }
}
